﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;

namespace RoadTeam.Pub
{
    public class ConverXML
    {
        /// <summary>
        /// 将DataTable对象转换成XML字符串
        /// 需要设置Datatabe 的名称
        /// </summary>
        /// <param name="dataTable">DataTable对象</param>
        /// <returns>XML字符串</returns>
        public static String ConvertDataTableToXml(DataTable dataTable)
        {
            MemoryStream memoryStream = null;
            XmlTextWriter xmlTextWriter = null;

            if (dataTable != null)
            {
                try
                {
                    memoryStream = new MemoryStream();
                    //根据ms实例化XmlWt
                    xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.Unicode);
                    //获取ds中的数据
                    dataTable.WriteXml(xmlTextWriter);
                    Int32 count = (Int32)memoryStream.Length;
                    byte[] temp = new byte[count];
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    memoryStream.Read(temp, 0, count);

                    //返回Unicode编码的文本
                    UnicodeEncoding ucode = new UnicodeEncoding();
                    string returnValue = ucode.GetString(temp).Trim();
                    return returnValue;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    if (xmlTextWriter != null)
                    {
                        xmlTextWriter.Close();
                        memoryStream.Close();
                        memoryStream.Dispose();
                    }
                }
            }
            return String.Empty;
        }


 
    }
}
